package com.chuyi.demo.frame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.Border;


public class DefaultListModelExample extends JFrame{

	private DefaultListModel sampleModel;
	private JList sampleJList;

	public DefaultListModelExample(){
		
		Container container = getContentPane();
		
	    String[] entries = { "Entry 1", "Entry 2", "Entry 3",
                "Entry 4", "Entry 5", "Entry 6" };
	    sampleModel = new DefaultListModel();
		
	    for(int i=0; i<entries.length; i++){
	    	 sampleModel.addElement(entries[i]);
	    }
	       
	    sampleJList = new JList(sampleModel);
	    sampleJList.setVisibleRowCount(4);
	    Font displayFont = new Font("Serif", Font.BOLD, 18);
	    sampleJList.setFont(displayFont);
	    JScrollPane listPane = new JScrollPane(sampleJList);
	    JPanel listPanel = new JPanel();
	    listPanel.setBackground(Color.white);
	    Border listPanelBorder =
	      BorderFactory.createTitledBorder("Sample JList");
	    listPanel.setBorder(listPanelBorder);
	    listPanel.add(listPane);
	    container.add(listPanel, BorderLayout.CENTER);
	    
	    
	    JButton addButton = new JButton("Add Entry to Bottom of JList");
	    addButton.setFont(displayFont);
	    addButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				int index = sampleModel.getSize();
			      sampleModel.addElement("Entry " + (index+1));
			      getContentPane().invalidate();
			      getContentPane().validate();
			      sampleJList.setSelectedIndex(index);
			      sampleJList.ensureIndexIsVisible(index);
			}
		});
	     
	    JPanel buttonPanel = new JPanel();
	    buttonPanel.setBackground(Color.white);
	    Border buttonPanelBorder =BorderFactory.createTitledBorder("Adding Entries");
	    buttonPanel.setBorder(buttonPanelBorder);
	    buttonPanel.add(addButton);
	    container.add(buttonPanel, BorderLayout.SOUTH);
	    
		pack();
		setVisible(true);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}
	
	public static void main(String[] args) {
		
		new DefaultListModelExample();
	}
	
}
